<?php

namespace App\Console\Commands\BlockPool;

use App\Models\Account;
use App\Models\GiveU;
use App\Models\GiveURewad;
use App\Models\Profit;
use App\Models\Setting;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ReleaseStatic extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'release-static';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '抢U获得千分之一YTB';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * 挖矿算力：自己抢U金额千分之一
     * 当日抢U≥4人
     * 团队日收益≥40U
     * 人数计算规则：
     * 当日抢U人数=当日0-24时期间（出场时间所在的0-24）抢U结束的人数。同一个人员重复下订单不计入人数统计内，自己不计算在内。
     * 团队日收益=当日0-24时期间（出场时间所在的0-24）抢U结束的全部订单的收益
     *
     * 每天0:10结算前一天
     * @return mixed
     */
    public function handle()
    {
        logger('==抢U获得YTB结算==');
        $users = User::all();
        foreach ($users as $user) {
            $this->profit($user);
        }
    }

    public function profit($user)
    {
        logger($user);
        $start = Carbon::now()->startOfDay()->subDay();
        $end = Carbon::now()->endOfDay()->subDay();
        // 是否参与抢U用户
        if (!GiveURewad::where('status', 1)->where('user_id', $user->id)->whereBetween('created_at', [$start, $end])->exists()) {
            logger('没有参与抢U，不结算');
            return;
        }

        $user_ids = User::where('_lft', '>', $user->_lft)
            ->where('_rgt', '<', $user->_rgt)
            ->pluck('id');
        // 当日抢U≥4人
        $childGiveUReward = GiveURewad::whereIn('user_id', $user_ids)->where('status', 1)->whereBetween('created_at', [$start, $end])->distinct('user_id')->pluck('user_id');
        logger("抢U人数：".count($childGiveUReward));
        // 团队日收益≥40U
        $reward = GiveURewad::whereIn('user_id', $user_ids)->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('reward');
        logger("团队日收益：{$reward}");
        // 该用户当天总计抢U数量
        $userReward = GiveURewad::where('user_id', $user->id)->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('num');
        logger('自己抢U数量：'.$userReward);
        // 自己抢U有效数量（用户抢U结束的时刻，团队中是否存在正在抢U的其它用户。如果不存在，则用户抢U不发放以太币）
        $userRewardList = GiveURewad::where('user_id', $user->id)->where('status', 1)->whereBetween('created_at', [$start, $end])->get();
        $effectiveReward = 0;
        foreach ($userRewardList as $item) {
            $giveuEnd = $item->update_at;
            $giveuStart = date("Y-m-d H:i:s", (strtotime($item->update_at) - 42000));
            if (GiveU::whereIn('user_id', $user_ids)->whereBetween('created_at', [$giveuStart, $giveuEnd])->exists()) {
                $effectiveReward += $item->num;
            }
        }
        logger('自己抢U有效数量：'.$effectiveReward);
        if ($effectiveReward <= 0) {
            logger('团队中没有正在抢U的其它用户，不结算');
            return;
        } else {
            $userReward = $effectiveReward; // 用自己抢U有效数量结算
        }

        $ytb_rate = Setting::where('key', 'ytb_rate')->value('value') ?: 0.008;
        $account = Account::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => 2
        ])->refresh();
        // 抢U获得YTB明细
        $profit = new Profit();
        $profit->user_id = $account->user_id;
        $profit->freeze = $userReward;
        $profit->rate = $ytb_rate;
        $profit->profit = bcmul($userReward, $profit->rate);
        $profit->time = now();
        if ($profit->profit > 0 && !Profit::where('user_id', $account->user_id)->whereDate('time', today())->exists()) { // 今天没有结算过
            logger("奖励YTB数量：{$profit->profit}");
            DB::transaction(function () use ($profit, $account, $childGiveUReward, $reward) {
                $profit->save();

                // 保存账户
                /** @var Account $account */
                $account = Account::lockForUpdate()->find($account->id);
                if (count($childGiveUReward) >= 4 && $reward >= 40) {
                    $account->availableIncrement($profit->profit);
                    $account->type = '解冻';
                } else {
                    $account->disabledIncrement($profit->profit);
                    $account->type = '抢U获得';
                }
                $account->action_id = $profit->id;
                $account->save();
            });
        }
    }
}
